/**
 * @author jjisaac
 */
var ias = null;
var curImg = new Image();
var tgCounter = 1;
var tagSets = [];

function activateTag(){
    toggleViewBarImg(false, 'Click <br> Image');
    toggleTag(false);
    var tgVBB = $gel('tagViewButtonBar');
    $('#tagViewButtonBar').html('');
    var tagBt = document.createElement('button');
    tagBt.id = 'tgBut';
    $(tagBt).html('Tag');
    tagBt.className = 'tgbutton';
    var tagCancelBt = document.createElement('button');
    tagCancelBt.id = 'tgCancel';
    $(tagCancelBt).html('Cancel');
    tagCancelBt.className = 'tgbutton';
    var tagDeactBt = document.createElement('button');
    tagDeactBt.id = 'tgDeAct';
    $(tagDeactBt).html('Deactivate');
    tagDeactBt.className = 'tgbutton';
    tgVBB.appendChild(tagBt);
    tgVBB.appendChild(brln());
    tgVBB.appendChild(tagCancelBt);
    tgVBB.appendChild(brln());
    tgVBB.appendChild(tagDeactBt);
    
    ias = $('img#svImgld').imgAreaSelect({
        fadeSpeed: 300,
        handles: true,
        instance: true,
        closeButton: 'tgCancel',
        aspectRatio: '1:1',
        onSelectChange: preview,
        deactivateButton: 'tgDeAct',
        activateButton: 'tgAct',
        tagButton: 'tgBut'
    });
    
    ias.imgObj.bind('click', initSelector);
}

function toggleVC(element, stl){
    $('#' + element).uncorner();
    if ($('#' + element).attr('actv') == 'on') {
        $('#' + element).corner();
    }
    else {
        $('#' + element).corner(stl);
    }
}

function appendLdBar(container){
    var loaderBar = ldBar(0, 0);
    document.body.appendChild(loaderBar);
    centerWN(container, loaderBar.id);
}

function ldBar(top, left){
    var ldBarImage = document.createElement('img');
    var ldBarImageDiv = document.createElement('div');
    ldBarImageDiv.className = 'loader';
    ldBarImage.src = 'images/loading_min.gif';
    ldBarImageDiv.appendChild(ldBarImage);
    ldBarImageDiv.appendChild(brln());
    ldBarImageDiv.innerHTML += 'loading';
    ldBarImageDiv.style.top = top + 'px';
    ldBarImageDiv.style.left = left + 'px';
    ldBarImageDiv.id = 'ldBar';
    return ldBarImageDiv;
}

function removeLdBar(){
    $('#ldBar').remove();
}

function loadImage(container, url, callback){
    $(curImg).load(function(){
        this.style.cssText = 'display: none;';
        this.id = 'svImgld';
        $('#' + container).append(this);
        
        $('#' + container).animate({
            height: $(this).height(),
            "easing": "easeout",
        }, 700, function(){
            $(curImg).fadeIn(500);
        });
        removeLdBar();
    }).attr('src', 'images/1.jpg');
    ;
    
}

function buttonDiv(id, inText){
    var btDiv = document.createElement('div');
    btDiv.id = id;
    $(btDiv).html('Text');
}

function brln(){
    return document.createElement('br');
}

function initSelector(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    selector(this, 100, 100, x, y, false, ias);
    ias.selectOn();
}

function selector(clkEml, width, height, mouseX, mouseY, start, ias){
    var selWidth = width, selHeight = height;
    var x1, x2, y1, y2;
    if (start) {
        x1 = mouseX - (width / 2);
        y1 = mouseY - (height / 2);
    }
    else {
        if ((mouseX < (width / 2)) && (mouseY < (height / 2))) {
            x1 = 5;
            y1 = 5;
            //$('#pValue').append('##Close to left corner top##');
        }
        else 
            if (($(clkEml).width() - mouseX) < (width / 2) && (mouseY < (height / 2))) {
                x1 = $(clkEml).width() - (width + 5);
                y1 = 5;
            //$('#pValue').append('##Close to right corner top##');
            }
            else 
                if ((mouseX < (width / 2)) && (($(clkEml).height() - mouseY) < (height / 2))) {
                    x1 = 5;
                    y1 = $(clkEml).height() - (height + 5);
                //$('#pValue').append('##Close to left corner bottom##');
                }
                else 
                    if (($(clkEml).width() - mouseX) < (width / 2) && (($(clkEml).height() - mouseY) < (height / 2))) {
                        x1 = $(clkEml).width() - (width + 5);
                        y1 = $(clkEml).height() - (height + 5);
                    //$('#pValue').append('##Close to right corner bottom##');
                    }
                    else 
                        if (!(mouseX < (width / 2)) && (mouseY < (height / 2))) {
                            x1 = mouseX - (width / 2);
                            y1 = 5;
                        //$('#pValue').append('##Close to top## >>'+clkEml.offsetTop);
                        }
                        else 
                            if (!(mouseX < (width / 2)) && (($(clkEml).height() - mouseY) < (height / 2))) {
                                x1 = mouseX - (width / 2);
                                y1 = $(clkEml).height() - (height + 5);
                            //$('#pValue').append('##Close to bottom## >>'+clkEml.offsetTop);
                            }
                            else 
                                if ((mouseX < (width / 2)) && !(mouseY < (width / 2))) {
                                    x1 = 5;
                                    y1 = mouseY - (height / 2);
                                //$('#pValue').append('##Close to left## >>'+clkEml.offsetTop);
                                }
                                else 
                                    if (($(clkEml).width() - mouseX) < (width / 2)) {
                                        x1 = $(clkEml).width() - (width + 5);
                                        y1 = mouseY - (height / 2);
                                    //$('#pValue').append('##Close to right## >>'+clkEml.offsetTop);
                                    }
                                    else {
                                        x1 = mouseX - (width / 2);
                                        y1 = mouseY - (height / 2);
                                    }
    }
    x2 = x1 + width;
    y2 = y1 + height;
    
    ias.setOptions({
        show: true,
        x1: mouseX - 1,
        y1: mouseY - 1,
        x2: mouseX + 1,
        y2: mouseY + 1
    });
    ias.animateSelection(x1, y1, x2, y2, 500);
}

$.extend($.imgAreaSelect, {
    animate: function(fx){
        var start = fx.elem.start, end = fx.elem.end, now = fx.now, curX1 = Math.round(start.x1 + (end.x1 - start.x1) * now), curY1 = Math.round(start.y1 + (end.y1 - start.y1) * now), curX2 = Math.round(start.x2 + (end.x2 - start.x2) * now), curY2 = Math.round(start.y2 + (end.y2 - start.y2) * now);
        fx.elem.ias.setSelection(curX1, curY1, curX2, curY2);
        fx.elem.ias.update();
        return fx;
    },
    prototype: $.extend($.imgAreaSelect.prototype, {
        animateSelection: function(x1, y1, x2, y2, duration){
            toggleViewBarImg(true, null);
            var fx = $.extend($('<div/>')[0], {
                ias: this,
                start: this.getSelection(),
                end: {
                    x1: x1,
                    y1: y1,
                    x2: x2,
                    y2: y2
                }
            });
            if (!$.imgAreaSelect.fxStepDefault) {
                $.imgAreaSelect.fxStepDefault = $.fx.step._default;
                $.fx.step._default = function(fx){
                    return fx.elem.ias ? $.imgAreaSelect.animate(fx) : $.imgAreaSelect.fxStepDefault(fx);
                };
            }
            $(fx).animate({
                cur: 1
            }, duration, function(){
                ias.changeView();
                var tagBar = $('#tagBar');
                ias.resetTVB(tagBar, tagBar.offset().left, tagBar.offset().top, tagBar.offset().left, ((ias.imgObj.offset().top + ias.getSelection().y1) - 7), 300, false);
            });
        }
    })
});
function preview(img, selection){
    var scaleX = 100 / (selection.width || 1);
    var scaleY = 100 / (selection.height || 1);
    $('#tagView > img').css({
        width: Math.round(scaleX * $(img).width()) + 'px',
        height: Math.round(scaleY * $(img).height()) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
}

function toggleTag(state){
    $('#tagBar').toggleClass('tagInActive');
    $('#imgCont').toggleClass('picInActive');
    if (state == 'off') {
        resetTagViewBar();
    }
}

function resetTagViewBar(){
    ias.imgObj.unbind('click');
    $('#tagViewButtonBar').html('');
    var actBt = document.createElement('button');
    $(actBt).html('Activate');
    actBt.onmouseup = function(){
        activateTag();
    };
    $gel('tagViewButtonBar').appendChild(actBt);
    toggleViewBarImg(false, 'Tag<br>Photo')
}

function toggleViewBarImg(isImg, msgTxt){
    var tagView = $('#tagView');
    tagView.html('');
    if (isImg) {
        var tagVwCpImg = $(curImg).clone();
        tagVwCpImg.id = 'tagVwCpImg';
        tagView.append(tagVwCpImg);
    }
    else {
        var tagMsg = elemCrt('tagMsg', 'div', null);
        $(tagMsg).html(msgTxt);
        tagView.append(tagMsg);
    }
}

/**
 * A DOM getter function similar to document.getElementById
 */
function $gel(){
    var elements = new Array();
    // Find all the elements supplied as arguments
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        // If the argument is a string assume it's an id
        if (typeof element == 'string') {
            element = document.getElementById(element);
        }
        // If only one argument was supplied, return the
        // element immediately
        if (arguments.length == 1) {
            return element;
        }
        // Otherwise add it to the array
        elements.push(element);
    }
    // Return the array of multiple requested elements
    return elements;
}

function elemCrt(id, tp, cls){
    var elmc = document.createElement(tp);
    //elmc
    id != null ? elmc.id = id : null;
    cls != null ? elmc.className = cls : null;
    
    return elmc;
}

/**
 * Function to get the size of the browser window
 */
function innerSize(){
    var myWidth = 0, myHeight = 0;
    if (typeof(window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    }
    else 
        if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        }
        else 
            if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
            }
    var bSize = {
        'X': myWidth,
        'Y': myHeight
    };
    return bSize;
}

/**
 * function to center element within specified client
 *
 * @param {Object} parent
 * @param {Object} centObj
 */
function centerWN(parent, centObj){
    var pObj = $('#' + parent), cntObj = $('#' + centObj);
    var pcX = (Math.round(pObj.width() / 2)) + pObj.offset().left;
    var pcY = (Math.round(pObj.height() / 2)) + pObj.offset().top;
    $gel(centObj).style.cssText = 'top:' + (pcY - (cntObj.height() / 2)) + 'px; left:' + (pcX - (cntObj.width() / 2)) + 'px';
}

function crtTag(width, height, top, left){
    var selTag_win = elemCrt('tg_window_' + tgCounter, 'span', 'tgWin');
    var selTag_in = elemCrt(null, 'span', 'tgIn');
    $(selTag_in).width(width);
    $(selTag_in).height(height);
    selTag_win.style.left = left + 'px';
    selTag_win.style.top = top + 'px';
    $(selTag_win).append(selTag_in);
    $('#imgTagBox').append(selTag_win);
    tgCounter++;
}

function activateTag(tagSets, isOn){

}

$.fn.tgUsropts = function(data){
    return this.each(function(){
        var select = this;
        $.each(data, function(index, itemData){
			var lbl = elemCrt('','label', null)
			var optn = new Option(itemData.text, itemData.value);
            $(lbl).append(option);
        });
    });
}
function tagClean(tgJson, name){
	var tempJson = [];
	var found = false;
	$.each(tgJson, function(index, itemData){
		itemData.name == name ? found = true :tempJson[index] = itemData[index];
	});
	tgJson = tempJson;
	return found;
}
function addTag(tagSets, name, top, left, width, height){
	if (!tagClean(tagSets, name)) {
		tagSets[tagSets.length] = {
			'name': name,
			'top': top,
			'left': left,
			'width': width,
			'height': height
		}
	}else{
		alert('exist');
	}
}
